/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void helper(TreeNode* root, int targetSum, int sum, vector<vector<int>>& res, vector<int>& tmp) {
        if (!root) return;
        tmp.push_back(root->val);
        sum += root->val;
        if (!root->left && !root->right) {
            if (sum == targetSum) res.push_back(tmp); 
        }
        helper(root->left, targetSum, sum, res, tmp);
        helper(root->right, targetSum, sum, res, tmp);
        tmp.pop_back();
        sum -= root->val;
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> res;
        vector<int> tmp;
        helper(root, targetSum, 0, res, tmp);
        return res;
    }
};